package org.wwb.antbox.user.web.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.ant.mybatis.support.MultiRouteDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Bond
 * @Date: 2020/3/3 17:54
 * @Description: 用户服务 数据源配置
 */
@Configuration
public class UserDataSourceAutoConfiguration {

    private DruidDataSource getBaseDruidDataSource(DruidDataSource druidDataSource){
        // 打开removeAbandoned功能
        druidDataSource.setRemoveAbandoned(true);
        // 1800秒，也就是30分钟
        druidDataSource.setRemoveAbandonedTimeout(1800);
        druidDataSource.setLogAbandoned(true);
        druidDataSource.setValidationQueryTimeout(30000);
        druidDataSource.setValidationQuery("SELECT 1");
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setTestWhileIdle(true);
        // 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
        // 配置一个连接在池中最小生存的时间，单位是毫秒
        druidDataSource.setMinEvictableIdleTimeMillis(180000);
//        druidDataSource.setFilters("config");
//        druidDataSource.setConnectionProperties("config.decrypt="+decrypt);
        return druidDataSource;
    }

    @Primary
    @Bean(name = "masterDataSource",destroyMethod = "close")
    @ConditionalOnMissingBean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "app.datasource.master")
    public DruidDataSource masterDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource =getBaseDruidDataSource(druidDataSource);
        return druidDataSource;
    }

    @Bean(name = "slaveDataSource",destroyMethod = "close")
    @ConditionalOnMissingBean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "app.datasource.slave")
    public DruidDataSource slaveDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource =getBaseDruidDataSource(druidDataSource);
        return druidDataSource;
    }

    /**
     * 多数据源
     * @return MultiRouteDataSource
     */
    @Bean(name = "multiDataSource")
    public MultiRouteDataSource multiRouteDataSource() {
        MultiRouteDataSource multiDataSource = new MultiRouteDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource());
        targetDataSources.put("slave", slaveDataSource());
        multiDataSource.setTargetDataSources(targetDataSources);
        multiDataSource.setDefaultTargetDataSource(masterDataSource());
        return multiDataSource;
    }
}
